<?php

class CommonApp extends Controller{

    public function _initialize() {
    	C('SHOW_PAGE_TRACE',(My::arr2var($_GET,'debug')=='true' OR C('SHOW_PAGE_TRACE')==true)?true:false);//debug调试
		//上一页面url
		define('URL_', (My::user('URL_'))?My::user('URL_'):empty($_SERVER['HTTP_REFERER'])?"":$_SERVER['HTTP_REFERER']);
    	self::setcookie();//设置相关cookie变量供前端用
    	self::commonData();
	}
	
	/**
	 * 设置相关cookie变量供前端用
	 */
	private function setcookie(){
		setcookie("__ROOT__", __ROOT__,null,__ROOT__);
		setcookie("__PROJECT__", __PROJECT__,null,'/');
	}

	/**
	 * 跳转函数(兼容函数)
	 * by huanran.zhao
	 */
	function ajaxReturn($statusCode, $message, $callbackType = '', $forwardUrl = '', $data='') {
		//404页面,使用方法$this->ajaxReturn(404,'找不到页面');
		if($statusCode==404){
			$this->assign('title',$message);
			$this->display('404');
			exit();
		}
		//ajaxsubmit方式提交的表单(表单验证方式)
		if(My::is_ajax()){
			$jsonData = array(
								'statusCode' => $statusCode,
								'message' => $message,
								'forwardUrl' => $forwardUrl,
								'data' => $data
							 );
			exit(json_encode($jsonData));
		}
		//正常方式页面跳转
		else{
			if(isset($_GET['URL'])) $URL=$_GET['URL'];//将get赋值给post
			if(isset($_POST['URL_'])) $URL_=$_POST['URL_'];//将get赋值给post
			//有传参时,强行按这个跳转url=$url
			if(!empty($url)) $URL=$URL_=$url;
			if(My::user('URL_')) $URL_=My::user('URL_');
			//默认
			if(empty($URL)) $URL = URL;
			if(empty($URL_)) $URL_ = URL_;
			
			$this->assign("text",$message);
			$this->assign("time",2);
			if($statusCode==200){
				unset($_SESSION['URL_']);
				$this->assign("url",$URL_);//成功:返回上一页面URL_
			}else{
				$_SESSION['URL_'] = $URL_;
				$this->assign("url",$URL);//失败:返回上一页面
			}
			exit(json_encode(array('statusCode'=>$statusCode,'message'=>$message)));
		}
	}

	//左菜单与面包屑
	function menu($item=''){
	    if($item=='')
	        return false;
	    $menu = array();
	    if(in_array($item,array('intro','leader','venues','student'))){
	        $menu['title'] = '学院概况';
	        $menu['app'] = 'intro';
	        $menu['act'] = 'intro';
	        $menu['submenu'] = array(
	            'intro'=>'学院简介',
	            'leader'=>'现任领导',
	            'venues'=>'场地介绍',
	            // 'student'=>'学生组织',
	        );
	    }else if(in_array($item,array('country','province','school'))){
	        $menu['title'] = '政策法规';
	        $menu['app'] = 'policy';
	        $menu['act'] = 'country';
	        $menu['submenu'] = array(
	            'country'=>'国家政策',
	            'province'=>'省市政策',
	            'school'=>'学校政策',
	        );
	    }else if(in_array($item,array('chair','classes','project','game','salon','practice'))){
	        $menu['title'] = '创业教育';
	        $menu['app'] = 'activity';
	        $menu['act'] = 'chair';
	        $menu['submenu'] = array(
	        	'chair'=>'创业大讲堂',
	        	'classes'=>'创业课程',
	        	'project'=>'大创项目',
	            'game'=>'创业大赛',
	            'salon'=>'创业沙龙',
	            'practice'=>'创业培训',
	            //'member'=>'会员列表',
	        );
	    }else if(in_array($item,array('section','activities'))){
	        $menu['title'] = '素拓中心';
	        $menu['app'] = 'quality';
	        $menu['act'] = 'section';
	        $menu['submenu'] = array(
	        	'section'=>'素拓部门',
	        	'activities'=>'素拓活动',
	        );
	    }else if(in_array($item,array('base','inside','outside'))){
	        $menu['title'] = '创业基地';
	        $menu['app'] = 'study';
	        $menu['act'] = 'base';
	        $menu['submenu'] = array(
	            'base'=>'基地介绍',
	            'inside'=>'校内基地',
	            'outside'=>'校外基地',
	        );
	    }else if(in_array($item,array('in','out','honor'))){
	        $menu['title'] = '创业导师';
	        $menu['app'] = 'sir';
	        $menu['act'] = 'in';
	        $menu['submenu'] = array(
	            'in'=>'校内导师',
	            'out'=>'校外导师',
	            'honor'=>'导师荣誉',
	        );
	    }else if(in_array($item,array('team','event'))){
	        $menu['title'] = '创业团队';
	        $menu['app'] = 'result';
	        $menu['act'] = 'team';
	        $menu['submenu'] = array(
	        	'team'=>'杰出团队',
	            'event'=>'成果展示',
	        );
	    }else if(in_array($item,array('work','quality','teach','innovate','race'))){
	        $menu['title'] = '办事指南';
	        $menu['app'] = 'guide';
	        $menu['act'] = 'work';
	        $menu['submenu'] = array(
	            'work'=>'孵化基地办事指南',
	            'quality'=>'素拓中心办事指南',
	            'teach'=>'课程教学办事指南',
	            'innovate'=>'大创项目办事指南',
	            'race'=>'竞赛活动办事指南',
	        );
	    }else if(in_array($item,array('contact'))){
	        $menu['title'] = '联系我们';
	        $menu['app'] = 'contact';
	        $menu['act'] = 'index';
	    // }else if($item == 'download'){
	    //     $menu['title'] = '下载专区';
	    //     $menu['app'] = 'download';
	    //     $menu['act'] = 'index';
	    //     $menu['submenu'] = array(
	    //         'index'=>'下载专区',
	    //     );
	    }else if(in_array($item,array('download','policy','article','sutuo','tutor','record'))){
	        $menu['title'] = '下载专区';
	        $menu['app'] = 'download';
	        $menu['act'] = 'download';
	        $menu['submenu'] = array(
	            'download'=>'通用文件下载',
	            'policy'=>'政策文件下载',
	            'article'=>'项目文件下载',
	            'sutuo'=>'素拓文件下载',
	            'tutor'=>'导师资料下载',
	            'record'=>'成果档案下载',
	        );
	    }else if($item == 'news'){
	    	$menu['title'] = '新闻动态';
	        $menu['app'] = 'news';
	        $menu['act'] = 'news';
	        $menu['submenu'] = array(
	            'news'=>'新闻动态',
	        );
	    }else if($item == 'announ'){
	    	$menu['title'] = '通知公告';
	        $menu['app'] = 'news';
	        $menu['act'] = 'news';
	        $menu['submenu'] = array(
	            'announ'=>'通知公告',
	        );
	    }else if($item == 'space'){
	    	$menu['title'] = '创客空间';
	        $menu['app'] = 'hackerspace';
	        $menu['act'] = 'space';
	        $menu['submenu'] = array(
	            'space'=>'创客空间',
	        );
	    }
	    return $menu;
	}
	
	//seo
	function assign_seo($item=''){
	    if($item=='')
	        return false;
	    $alias = $item.'_seo';
	    $seo = My::alias2detail('config',$alias);
	    if(!$seo or $seo<0)
	        return false;
        $this->assign('seo_title',My::arr2var($seo,'params.seo_title'));
        $this->assign('seo_keywords',My::arr2var($seo,'params.seo_keywords'));
        $this->assign('seo_description',My::arr2var($seo,'params.seo_description'));
	}

	private function commonData(){
	    //通用数据
        $unified = My::alias2detail('config','index');
        $this->assign('unified',$unified);
	}

	//文章详情
	function detail($id=''){
        $result = My::id2detail('datas',$id,array('publish'=>1,'has_page'=>true));
        // $result['item_zh'] = DB('category')->where('item ="'.$item.'"')->field('title')->find();
        //编辑器缩略图显示
        $result['content'] = My::img_replace($result['content']);
        //防止重复刷新
        if (empty($_COOKIE['hit_id']) || $_COOKIE['hit_id'] != $id){
            setcookie('hit_id',$id,time()+600);
            ++$result['hit'];
            My::setField('datas',$id,array('key'=>'hit','value'=>$result['hit']));
        }
        $result['new'] = My::item2list('datas',$result['item'],array('publish' => 1));//最新
        $result['hit_n'] = DB('datas')->where('item ="'.$result['item'].'"')->order('hit DESC,hot DESC,id DESC')->limit('13')->field('id,title,params')->select();
        foreach ($result['hit_n'] as &$value) {
            $value['params'] = My::decodeJson($value['params']);
        }//最热
        return $result;
	}

	//分页
    function getList($item='',$pagesize='6'){
    	if($item=='')
	        return false;
        $page = I('get.page',1);
        $total = DB('datas')->where("`item`='{$item}' AND publish=1")->cache()->count();
        $result['page'] = My::page($total,array('pagesize'=>$pagesize));
        $result['data'] = My::item2list('datas',$item,array('pagesize'=>$pagesize,'page'=>$page,'publish'=>1,'order'=>'hot'));
        if(is_array($result['data']))
            foreach($result['data'] as &$value){
                //去掉html标签
                $value['content'] = trim(strip_tags(My::decodeHtml($value['content'])));
                //截取前150个字符
                $value['desc'] = mb_substr($value['content'], 0,150,'utf-8');
        }
        foreach ($result['data'] as &$value) {
            $value['times'] = floor((NOW_TIME-strtotime($value['adddate']))/86400);
        }
        return $result; 
    }
    
	/**
	 * 判断是否已登录,如未登录则跳转到登录页面
	 */
	public function checkLogin(){
	    if(!My::user('member.memberid')){
	        if(My::is_ajax())
	            $this->ajaxReturn('300','未登录!');
	        else{
	            //setCookie("history__url", $_SERVER["REQUEST_URI"], time()+31536000, "/");
	            redirect(Router::encodeUrl('index.php?app=Login'));
	        }
	    }else{
	        if(!isset($_SESSION['member']['college_c'])){
                $_SESSION['member']['colleges'] =  M('admin.category')->item2submenu('college',array('level'=>'1'));//学院
                $_SESSION['member']['college_c'] = $_SESSION['member']['colleges'][$_SESSION['member']['college']]['title'];
                if(!empty($_SESSION['member']['class']) && $_SESSION['member']['type'] != '0')
                    $_SESSION['member']['class_c'] = DB('category')->where("id = {$_SESSION['member']['class']}")->getField('title');;//专业
//	            echo '没保存session,在刷新下';
//	            exit();
	        }
            $result = $_SESSION['member'];
            return $result;
        }
	}

	//身份非法访问
    protected function is_student(){
	    //非学生身份
	    if(My::user('member.type') != '2')
            redirect(Router::encodeUrl('index.php?app=Myproject&act=teacher'));//重定向老师
    }
    protected function is_teacher(){
        //非老师身份或者管理员身份
        if(My::user('member.type') == '2')
            redirect(Router::encodeUrl('index.php?app=Myproject&act=student'));//重定向学生
    }
}